package com.niit.service.impl;

import com.niit.bean.R;
import com.niit.dao.ProductRepository;
import com.niit.dao.RatingRepository;
import com.niit.dao.UserRepository;
import com.niit.entity.Product;
import com.niit.entity.Rating;
import com.niit.entity.User;
import com.niit.utils.Constant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Random;

@Service
@Slf4j
public class ABTestRatingService {

    @Autowired
    private RatingRepository ratingRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private ProductRepository productRepository;

    /**
     * 使用ab压测模拟用户打分时调用的接口
     * 拼接接口：http://localhost:9000/rating/rateProductByAB/userId/productId/score
     * @return
     */
    public R addRating() {

        List<User> userList = userRepository.findAll();          // 获取用户表数据
        List<Product> productList = productRepository.findAll(); // 获取商品表数据
        int userRandom = new Random().nextInt(userList.size());  // 产生用户随机数,范围[0,userList.size()-1]
        int productRandom = new Random().nextInt(productList.size()); // 产生商品随机数，范围[0,productList.size()-1]
        int scoreRandom = new Random().nextInt(5) + 1; // 产生随机的分值，范围在[1,5]

        Rating rating = new Rating();
        rating.setUserId(userList.get(userRandom).getUserId());
        rating.setProductId(productList.get(productRandom).getProductId());
        rating.setScore(Double.valueOf(scoreRandom));

        Integer timestamp = Long.valueOf(System.currentTimeMillis()/1000).intValue(); // 时间戳
        rating.setTimestamp(timestamp);
        ratingRepository.save(rating);
        //埋点：记录用用户打分行为
        log.info(Constant.PRODUCT_RATING_PREFIX + ":" + rating.getUserId() +"|"+ rating.getProductId() +"|"+ rating.getScore() +"|"+ System.currentTimeMillis()/1000);
        return R.ok().message("打分完成！！");
    }
}
